import React from "react";
import { Button, Input, Form, Notify } from "react-vant";
import axios from "axios";
import { useDispatch } from "react-redux";
import { loginSuccess } from "../../store/modules/user/userActions";
import { useNavigate, useSearchParams } from "react-router-dom";
export default () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  const onFinish = (values) => {
    axios.post("/api/login", values).then((resp) => {
      const { code, data, message } = resp.data;

      if (code === 200) {
        // 友好提示
        Notify.show({ type: "success", message });
        // 保存信息
        const { token, userInfo } = data;
        localStorage.setItem('token', token);
        dispatch(loginSuccess(userInfo))
        // 跳转页面
        navigate(-1)
      } else {
        Notify.show({ type: "danger", message });
      }
    });
  };  

  return (
    <Form
      form={form}
      onFinish={onFinish}
      footer={
        <div style={{ margin: "16px 16px 0" }}>
          <Button round nativeType="submit" type="primary" block>
            提交
          </Button>
        </div>
      }
    >
      <Form.Item
      >
        <h1 style={{ textAlign: 'center', flex: 1 }}>用户登录</h1>
      </Form.Item>
      <Form.Item
        rules={[{ required: true, message: "请填写用户名" }]}
        name="username"
        label="用户名"
      >
        <Input placeholder="请输入用户名" />
      </Form.Item>
      <Form.Item
        rules={[{ required: true, message: "请填写密码" }]}
        name="password"
        label="密码"
      >
        <Input placeholder="请输入密码" />
      </Form.Item>
    </Form>
  );
};
